/**
 * Copyright 2000 self.com.au
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License. (http://www.apache.org/licenses/LICENSE-2.0)
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed 
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for 
 * the specific language governing permissions and limitations under the License.
 *
 * <dhamma-message src="Atisha (11th century Tibetan Buddhist master)">
 * 	The greatest achievement is selflessness. The greatest worth is self-mastery.
 * 	The greatest quality is seeking to serve others. The greatest precept is continual awareness.
 * 	The greatest medicine is the emptiness of everything. The greatest action is not conforming with the worlds ways.
 * 	The greatest magic is transmuting the passions. The greatest generosity is non-attachment.
 * 	The greatest goodness is a peaceful mind. The greatest patience is humility.
 * 	The greatest effort is not concerned with results. The greatest meditation is a mind that lets go.
 * 	The greatest wisdom is seeing through appearances. 
 * </dhamma-message>
 *
 * @author Ashin Wimalajeewa
 */
package self.amigo.editor.cmd;

import java.awt.Point;
import java.awt.Rectangle;
import java.util.*;

import self.gee.*;
import self.gee.editor.*;

public class SelectionAlignment implements ICommand {
  public static final int ALIGN_TOPS = 0;
  public static final int ALIGN_BOTTOMS = 1;
  public static final int ALIGN_LEFTS = 2;
  public static final int ALIGN_RIGHTS = 3;

  public static final int ALIGN_H_CENTERS = 4;
  public static final int ALIGN_V_CENTERS = 5;
  
  private IDiagramEditor  editor;
  private List            deltas = new ArrayList();
  private List            selection = new ArrayList();
  private List            origXys = new ArrayList();
  private int             type;
  private int             max;
  
//  public SelectionAlignment( IDiagramEditor ed, List s, int t ) {
  public SelectionAlignment( IDiagramEditor ed, int t ) {
    editor = ed;
    ed.getSelectedElements( selection );
//    selection.addAll( s );
    max = selection.size();
//    dumpSelection();
    type = t;
    calculateDeltas();
  }
  
  public void execute() {
    align( false );
  }

  public void undo() {
    IDiagramLayer layer = editor.getSource().getContext();
    List refreshedElements = SelectionUtils.toNewElementList( selection, layer );
    layer.beginUpdate();
    for ( int cntr = 0; cntr < max; cntr++ ) {
      IGraphicElement elem = (IGraphicElement) refreshedElements.get( cntr );
      Point loc = (Point) origXys.get( cntr );
      elem.setLocation( loc.x, loc.y );
    }
    for ( int cntr = 0; cntr < max; cntr++ ) {
      IGraphicElement elem = (IGraphicElement) refreshedElements.get( cntr );
      if ( elem instanceof ILinkGraphic )
        ((ILinkGraphic) elem).refreshEndPoints();
    }
    layer.endUpdate();
    editor.setSelectedElements( refreshedElements );
    editor.getSource().redraw();
  }
  
  private void align( boolean inv ) {
    IDiagramLayer layer = editor.getSource().getContext();
    List refreshedElements = SelectionUtils.toNewElementList( selection, layer );
    layer.beginUpdate();
    for ( int cntr = 0; cntr < max; cntr++ ) {
      IGraphicElement elem = (IGraphicElement) refreshedElements.get( cntr );
      Integer delta = (Integer) deltas.get( cntr );
      int val = inv ? -delta.intValue(): delta.intValue();
      set( elem, val );
    }
    for ( int cntr = 0; cntr < max; cntr++ ) {
      IGraphicElement elem = (IGraphicElement) refreshedElements.get( cntr );
      if ( elem instanceof ILinkGraphic )
        ((ILinkGraphic) elem).refreshEndPoints();
    }
    layer.endUpdate();
    editor.setSelectedElements( refreshedElements );
    editor.getSource().redraw();
  }
  
  private void calculateDeltas() {
    int pos = queryMoveTo();
    for ( int cntr = 0; cntr < max; cntr++ ) {
      IGraphicElement elem = (IGraphicElement) selection.get( cntr );
      Rectangle rect = elem.getBounds();
      Integer diff = new Integer( getDelta(rect, pos) );
      deltas.add( diff );      
      
      Point xy = rect.getLocation();
      origXys.add( new Point(xy) );
    }
  }
  
  private int queryMoveTo() {
    IGraphicElement elem = (IGraphicElement) selection.get( 0 );
    Rectangle rect = elem.getBounds();
    int moveVal = get( rect );
    for ( int cntr = 1; cntr < max; cntr++ ) {
      elem = (IGraphicElement) selection.get( cntr );
      rect = elem.getBounds();
      int elemVal = get( rect );
      moveVal = check( elemVal, moveVal );
    }
    return moveVal;
  }
  
  private int getDelta( Rectangle r, int pos ) {
    int elemPos = get( r );
    switch ( type ) {
      case ALIGN_TOPS:
      case ALIGN_LEFTS:
      case ALIGN_H_CENTERS:
      case ALIGN_V_CENTERS:
        return pos - elemPos;
      case ALIGN_BOTTOMS:
        return pos - elemPos - r.height;
      case ALIGN_RIGHTS:
        return pos - elemPos - r.width;
      default:
        throw new IllegalStateException( "err.type.alignment.invalid" );
    }
  }
  
  private int get( Rectangle r ) {
    switch ( type ) {
      case ALIGN_TOPS:
        return r.y;
      case ALIGN_LEFTS:
        return r.x;
      case ALIGN_BOTTOMS:
        return r.y + r.height;
      case ALIGN_RIGHTS:
        return r.x + r.width;
      case ALIGN_V_CENTERS:
        return r.x + (r.width / 2);
      case ALIGN_H_CENTERS:
        return r.y + (r.height / 2);
      default:
        throw new IllegalStateException( "err.type.alignment.invalid" );
    }
  }
  
  private void set( IGraphicElement elem, int delta ) {
    Rectangle r = elem.getBounds();
    switch ( type ) {
      case ALIGN_TOPS:
        elem.setLocation( r.x, r.y + delta ); break;
      case ALIGN_BOTTOMS:
        elem.setLocation( r.x, get(r) + delta ); break;
      case ALIGN_LEFTS:
        elem.setLocation( r.x + delta, r.y ); break;
      case ALIGN_RIGHTS:
        elem.setLocation( get(r) + delta, r.y ); break;
      case ALIGN_H_CENTERS:
        elem.setLocation( r.x, r.y + delta ); break;
      case ALIGN_V_CENTERS:
        elem.setLocation( r.x + delta, r.y ); break;
      default:
        throw new IllegalStateException( "err.type.alignment.type" );
    }
  } 
  
  private int check( int currVal, int lastVal ) {
    switch ( type ) {
      case ALIGN_TOPS:
      case ALIGN_LEFTS:
      case ALIGN_H_CENTERS:
      case ALIGN_V_CENTERS:
        return Math.min( currVal, lastVal );
      case ALIGN_BOTTOMS:
      case ALIGN_RIGHTS:
        return Math.max( currVal, lastVal );
      default:
        throw new IllegalStateException( "err.type.alignment.type" );
    }
  }
}